package com.xxx.user.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.user.domain.User;
import com.xxx.user.query.UserQuery;
import com.xxx.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;

import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Api(tags = "用户接口类")
public class UserController {

    private final IUserService userService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public R<List<User>> findAll() {
        List<User> list = userService.findAll();
        return R.ok(list);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询一个")
    public R<User> findOne(@PathVariable Long id) {
        User one = userService.findOne(id);
        return R.ok(one);
    }

    @PostMapping
    @ApiOperation(value = "分页加条件查询")
    public PageInfo<User> queryPage(@RequestBody UserQuery userQuery) {

        List<User> lists = userService.queryPage(userQuery);
        return new PageInfo<User>(lists);//limit a,b
    }

    @PutMapping
    @ApiOperation(value = "根据id更新或增加")
    public R<Void> addOrUpdateUser(@RequestBody User user) {
        try {
            if (user.getId() == null || user.getId() == 0) {
                userService.addUser(user);
            } else {
                userService.updateUser(user);
            }
        } catch (Exception e) {
            return R.fail("用户名已经存在");
        }

        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一个")
    public R<Void> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
        } catch (Exception e) {
            return R.fail("删除失败");
        }
        return R.ok();
    }

    @PatchMapping//批量请求
    @ApiOperation(value = "批量删除")
    public R<Void> batchUsers(@RequestBody Long[] ids) {
        try {
            userService.batchUsers(ids);
        } catch (Exception e) {
            return R.fail("删除失败");
        }
        return R.ok();
    }
}
